<template>
  <div id="home" class="wrapper">
    <nav-bar class="home-nav">
      <div slot="center">购物街</div>
    </nav-bar>
    <tab-control
      class="tab-show"
      v-show="isTabControlShow"
      :titles="titles"
      @tabClick="tabClick"
      ref="tabControl1"
    />
    <scroll
      class="content"
      :pullUpLoad="true"
      @scroll="homeScroll"
      @pullingUp="upLoadMore"
      :probe-type="3"
      ref="home"
    >
      <!-- 通过ref去调用Scroll组件中的方法以及变量，然后对他操作 -->
      <home-swiper :banners="banners" @swperImageLoad="swperImageLoad" />
      <recmommend-view :recommends="recommends" />
      <feature-view />
      <tab-control :titles="titles" @tabClick="tabClick" ref="tabControl2" />
      <!-- tabClick子组件传过来的事件（参数也能传递） -->
      <goods-list :goods="showGoods" />
      <!-- <div>{{recommends}}</div> -->
    </scroll>
  </div>
</template>

<script>
import HomeSwiper from "./chidComps/HomeSwiper";
import FeatureView from "./chidComps/featureView";
import RecmommendView from "./chidComps/RecommendView";

import Scroll from "components/common/scroll/BetterScroll";
import NavBar from "components/common/navbar/NavBar";
import TabControl from "components/content/tabcontrol/TabControl";
import GoodsList from "components/content/goods/GoodsList";

import { getHomeMultidata, getHomeGoods } from "network/home";
export default {
  name: "Home",
  data() {
    return {
      banners: [],
      recommends: [],
      titles: ["流行", "新款", "精选"],
      goods: {
        pop: { page: 0, list: [] },
        new: { page: 0, list: [] },
        sell: { page: 0, list: [] }
      },
      currentType: "pop",
      tabOffsetTop: 0,
      isTabControlShow: false,
      saveY:0/* 保存离开时的Y值 */
    };
  },
  components: {
    NavBar,
    HomeSwiper,
    RecmommendView,
    FeatureView,
    TabControl,
    GoodsList,
    Scroll
  },
  created() {
    // 请求多个首页数据
    this.getHomeMultidata();
    // 请求商品数据
    this.getHomeGoods("pop");
    this.getHomeGoods("new");
    this.getHomeGoods("sell");
  },
  mounted() {
    /* 采用事件总线方法刷新scroll，还需加上防抖 */
    /*  this.$bus.$on("itemImageLoad", () => {
      console.log("-----");
      this.$refs.home.refresh()
    }); 
    这里是拿到组件中的scroll，然后调用组件中定义的refresh（）方法*/
    /* 防抖函数操作 图片加载完后的事件监听*/
    const refresh = this.debounce(this.$refs.home.refresh, 200);
    /* 这里是拿到组件中的refresh方法最为参数传递，并不调用这个方法 */
    this.$bus.$on("itemImageLoad", () => {
      refresh();
    });
  },
  destroyed() {
    console.log('---');
  },
  activated() {
    this.$refs.home.scrollTo(0,this.saveY)
    this.$refs.home.refresh() 
  },
  deactivated() {
    this.saveY=this.$refs.home.getScrollY()
  },
  methods: {
    /**
     * 事件监听相关
     */
    tabClick(index) {
      /* 组件传过来的index，此处函数名为自定义 */
      switch (index) {
        case 0:
          this.currentType = "pop";
          break;
        case 1:
          this.currentType = "new";
          break;
        case 2:
          this.currentType = "sell";
          break;
      }
      /* 点击其他页面时，回到货物推荐顶部 */
    this.$refs.home.scroll.scrollTo(0,-this.tabOffsetTop)
    // 统一俩个tab-control的currentIndex
    this.$refs.tabControl1.currentIndex=index
    this.$refs.tabControl2.currentIndex=index
    },
    /**
     * 网路请求相关
     * */
    getHomeMultidata() {
      // 请求多个数
      getHomeMultidata().then(res => {
        this.banners = res.data.banner.list;
        // console.log("res: ", res);
        this.recommends = res.data.recommend.list;
      });
    },
    // 请求商品数据(推荐、新款、精选)
    getHomeGoods(type) {
      const page = this.goods[type].page + 1;
      getHomeGoods(type, page).then(res => {
        // console.log(res.data.list)
        /* 往数组末尾添加,并且使用参数结构，不能直接赋值，否则指向变化 */
        this.goods[type].list.push(...res.data.list);
        /*   console.log(`goods/${type}:`, this.goods[type].list); */
        /* 请求成功后页码加一 */
        this.goods[type].page += 1;
        /* 页码加一后下拉完成 */
        this.$refs.home.finishPullUp();
        /* 下拉完成后计算Scroll */
        // this.$refs.home.refresh()
        /* 这种方法和homeScroll（）结合使用，可模拟下拉弹起效果 */
        /* if(this.goods[type].page-1===0)
        this.$refs.home.refresh() */
      });
    },
    homeScroll(position) {
      /* 拿到子组件中的scroll，然后进行刷新scroll,position为子组件传递过来的position */
      // if (position.y < this.$refs.home.y) {
      //   this.$refs.home.refresh();
      // console.log(position);
      // }
      // 决定tabControl是否吸顶（position：fixed）,实时监听滚动获取this.isTabControlFixed
      this.isTabControlShow = -position.y > this.tabOffsetTop;
      /*  console.log('position.y: ', position.y);
      console.log('this.tabOffsetTop: ', this.tabOffsetTop); */
    },
    upLoadMore() {
      this.getHomeGoods(this.currentType);
    },
    // 防抖
    debounce(func, delay) {
      let timer;
      return function(...args) {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(function() {
          func.apply(this, args);
        }, delay);
      };
    },
    swperImageLoad() {
      /* 获取tabControl的offsetTop */
      /* 所有的组件都有有个属性$el,用于获取组件的元素 */
      this.tabOffsetTop = this.$refs.tabControl2.$el.offsetTop;
    }
  },
  computed: {
    showGoods() {
      return this.goods[this.currentType].list;
    }
  }
};
</script>

<style lang="scss" scoped >
#home {
  height: calc(100vh - 52px);
  position: relative;
}
.home-nav {
  background-color: var(--color-tint);
  color: var(--color-background);
  // 原生滚动是navbar置顶
  /*    position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 9; */
}

// .tab-control {
//   position: sticky; /* 吸顶效果，但是很多浏览器不支持，且在使用better-scroll以后失效 */
//   top: 44px;
//   z-index: 9;
// }
/* 占位样式 */
.tab-show {
  position: relative;
  z-index: 12;
}
.content {
  position: absolute;
  height: calc(100vh - 96px);
  overflow: hidden;
  top: 44px;
  left: 0;
  right: 0;
}
</style>